package com.hmall.geteway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.geteway.config.AuthProperties;
import com.hmall.geteway.config.JwtProperties;
import com.hmall.geteway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
@EnableConfigurationProperties({JwtProperties.class,AuthProperties.class})
public class AuthGlobalFilter implements GlobalFilter {
    @Autowired
    private AuthProperties authProperties;

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Autowired
    private JwtTool jwtTool;

    /***
     * 用户登录身份拦截校验
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //0.获取Request和Response对象:获取用户传入的数据 Request,拦截需要用到Response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.校验访问地址是否是开放的地址,如果是,直接放行:有一些地址是开放的,比如登录
        String uri = request.getPath().toString();
        if(isExclude(uri)){
        return chain.filter(exchange);
        }
        //2.获取请求头令牌
        String token=request.getHeaders().getFirst("authorization");

        //3.检验令牌是否有效
        Long userId=null;

        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.just(response.bufferFactory().wrap("{\"msg\":\"请先登录!\"}".getBytes(StandardCharsets.UTF_8))));
        }
        //4. TODD有效,获取用户ID,并封装到请求头,可以传递给下游服务
        String userInfo=userId.toString().toString();
        exchange.mutate().request(builder -> builder.header("user-info",userInfo));
        //5,放行
        return  chain.filter(exchange);
    }
    /***
     * 匹配指定地址是否需要进行拦截
     */
    public boolean isExclude(String uri){
        return authProperties.getExcludePaths().stream().anyMatch(ep->antPathMatcher.match(ep,uri));
    }
}
